/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.b2b.modules.fm.web.base;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.b2b.common.service.BaseService;
import com.b2b.modules.fm.assets.FmConsts;
import com.b2b.modules.sys.entity.User;
import com.b2b.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.b2b.common.utils.DateUtils;
import com.b2b.common.utils.MyBeanUtils;
import com.b2b.common.config.Global;
import com.b2b.common.persistence.Page;
import com.b2b.common.web.BaseController;
import com.b2b.common.utils.StringUtils;
import com.b2b.common.utils.excel.ExportExcel;
import com.b2b.common.utils.excel.ImportExcel;
import com.b2b.modules.fm.entity.base.FmStore;
import com.b2b.modules.fm.service.base.FmStoreService;

/**
 * 门店管理Controller
 * @author soldier lee
 * @version 2016-11-15
 */
@Controller
@RequestMapping(value = "${adminPath}/fm/base/fmStore")
public class FmStoreController extends BaseController {

	@Autowired
	private FmStoreService fmStoreService;
	
	@ModelAttribute
	public FmStore get(@RequestParam(required=false) String id) {
		FmStore entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = fmStoreService.get(id);
		}
		if (entity == null){
			entity = new FmStore();
		}
		return entity;
	}
	
	/**
	 * 门店管理列表页面
	 */
	@RequiresPermissions("fm:base:fmStore:list")
	@RequestMapping(value = {"list", ""})
	public String list(FmStore fmStore, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(!UserUtils.isAdmin()) {
			fmStore.setSto000(Global.SHOW);
			fmStore.getSqlMap().put("dsf", BaseService.dataScopeFilter(UserUtils.getUser(), "o", "u"));
		}
		List<FmStore> list = fmStoreService.findList(fmStore);
		model.addAttribute("list", list);
		return "modules/fm/base/fmStoreList";
	}

	/**
	 * 查看，增加，编辑门店管理表单页面
	 */
	@RequiresPermissions(value={"fm:base:fmStore:view","fm:base:fmStore:add","fm:base:fmStore:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(FmStore fmStore, Model model) {
		if (StringUtils.isEmpty(fmStore.getId())){
			fmStore.setSto000(Global.SHOW);
			fmStore.setSto001(Global.YES);
			fmStore.setSto003(FmConsts.FmStoreStatus.on.toString());
			fmStore.setSto018(FmConsts.FmStore.TYPE_ZY.getIndex());
		}
		model.addAttribute("fmStore", fmStore);
		return "modules/fm/base/fmStoreForm";
	}

	/**
	 * 保存门店管理
	 */
	@RequiresPermissions(value={"fm:base:fmStore:add","fm:base:fmStore:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(FmStore fmStore, Model model) throws Exception{
		if (!beanValidator(model, fmStore)){
			return form(fmStore, model);
		}
		if(!fmStore.getIsNewRecord()){//编辑表单保存
			FmStore t = fmStoreService.get(fmStore.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(fmStore, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			fmStoreService.save(t);//保存
		}else{//新增表单保存
			fmStoreService.save(fmStore);//保存
		}
		model.addAttribute("errCode",200).addAttribute("message", "保存门店信息成功");
		return "modules/fm/base/fmStoreForm";
	}
	
	/**
	 * 删除门店管理
	 */
	@RequiresPermissions("fm:base:fmStore:del")
	@RequestMapping(value = "delete")
	public String delete(FmStore fmStore, RedirectAttributes redirectAttributes) {
		fmStoreService.delete(fmStore);
		addMessage(redirectAttributes, "删除门店管理成功");
		return "redirect:"+Global.getAdminPath()+"/fm/base/fmStore/?repage";
	}
	
	/**
	 * 批量删除门店管理
	 */
	@RequiresPermissions("fm:base:fmStore:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			fmStoreService.delete(fmStoreService.get(id));
		}
		addMessage(redirectAttributes, "删除门店管理成功");
		return "redirect:"+Global.getAdminPath()+"/fm/base/fmStore/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("fm:base:fmStore:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(FmStore fmStore, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "门店管理资料"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";fmStore.setSto000(Global.SHOW);
			fmStore.getSqlMap().put("dsf", BaseService.dataScopeFilter(UserUtils.getUser(), "o", "u"));
			List<FmStore> list = fmStoreService.findList(fmStore);
    		new ExportExcel("门店资料", FmStore.class).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出门店管理记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fm/base/fmStore/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("fm:base:fmStore:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<FmStore> list = ei.getDataList(FmStore.class);
			for (FmStore fmStore : list){
				try{
					fmStoreService.save(fmStore);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条门店管理记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条门店管理记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入门店管理失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fm/base/fmStore/?repage";
    }
	
	/**
	 * 下载导入门店管理数据模板
	 */
	@RequiresPermissions("fm:base:fmStore:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "门店管理数据导入模板.xlsx";
    		List<FmStore> list = Lists.newArrayList(); 
    		new ExportExcel("门店管理数据", FmStore.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fm/base/fmStore/?repage";
    }


	/**
	 * 根据门店编号 验证门店编号  唯一性
	 * @param sto002
	 * @param response
	 * @param model
     * @return
     */
	@ResponseBody
	@RequestMapping(value = "validateStoreNo")
	public boolean validateStoreNo(String sto002, HttpServletResponse response, Model model) {
		FmStore fmStore =  this.fmStoreService.findUniqueByProperty("sto002", sto002);
		if(fmStore != null){
			return true;
		}else{
			return false;
		}
	}

	@ResponseBody
	@RequestMapping(value = "validateSIM")
	public boolean validateSIM(String sto006, HttpServletResponse response, Model model) {
		FmStore fmStore =  this.fmStoreService.findUniqueByProperty("sto006", sto006);
		if(fmStore != null){
			return true;
		}else{
			return false;
		}
	}

	@ResponseBody
	@RequestMapping(value = "validateMno")
	public boolean validateMno(String sto005, HttpServletResponse response, Model model) {
		FmStore fmStore =  this.fmStoreService.findUniqueByProperty("sto005", sto005);
		if(fmStore != null){
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 选择门店
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "selectFmStore")
	public String selectFmStore(FmStore fmStore,String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) throws UnsupportedEncodingException {

		Page<FmStore> page =this.fmStoreService.findPage(new Page<FmStore>(request, response),fmStore );
		try {
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		model.addAttribute("labelNames", fieldLabels.split("\\|"));
		model.addAttribute("labelValues", fieldKeys.split("\\|"));
		model.addAttribute("fieldLabels", fieldLabels);
		model.addAttribute("fieldKeys", fieldKeys);
		model.addAttribute("url", url);
		model.addAttribute("searchLabel", searchLabel);
		model.addAttribute("searchKey", searchKey);
		model.addAttribute("obj", fmStore);
		model.addAttribute("page", page);
		return "modules/fm/base/gridselFmStore";
	}
	
	
	

}